/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package crowler;

import beans.ejb.NflplayerFacade;
import beans.ejb.NflplayergameFacade;
import beans.ejb.NflplayerseasonstatFacade;
import beans.ejb.NflteamFacade;
import entities.Nflplayerseasonstat;
import entities.Nflteam;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 *
 * @author The Lunatics
 */
public class CrowlerEssentials {

    public static final String TESTURL = "http://test.nfldata.com/api.svc";
    public static final String APIURL = "http://api.nfldata.com/api.svc";
    protected DocumentBuilder docBuilder;
    protected String lastResult = null;
    protected String season = null;
    protected String weekId = "yearweek";
    protected String playerId = null;
    public static final String licensekey = "c7fb0f65-ccb4-4965-bbb9-4cecd0890e10";
    protected List<Nflteam> teams;
    public static List<entities.Nflplayer> players;
    public static List<entities.Nflplayergame> playergames;
    public static List<entities.Nflplayerseasonstat> playerseasons;
    public static String returnPage = "crowler";
    private String tableName = "teamTable";
    @EJB
    private NflteamFacade teamFacade;
    @EJB
    private NflplayerFacade playerFacade;
    @EJB
    private NflplayerseasonstatFacade playerSeasonFacade;
    @EJB
    private NflplayergameFacade playerGamesFacade;
    /**
     * 1984-08-24T00:00:00
     */
    private static final SimpleDateFormat dateFormat =
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    /**
     * Creates a new instance of Crowler
     */
    public CrowlerEssentials() throws ParserConfigurationException {
        docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    }

    protected String getTextAsName(Element parent, String childName) {
        NodeList nl = parent.getElementsByTagName(childName);
        if (nl.getLength() == 0) {
            return null;
        }
        Element child = (Element) nl.item(0);
        Node firstChild = child.getFirstChild();
        if (firstChild != null) {
            return firstChild.getNodeValue();
        }
        return "";
    }

    protected Integer getIntegerAsName(Element parent, String ChildName) {
        String resultStr = getTextAsName(parent, ChildName);
        if (resultStr.equals("")) {
            return new Integer("0");
        } else {
            return new Integer(resultStr);
        }
    }

    protected Boolean getBooleanAsName(Element parent, String ChildName) {
        String result = getTextAsName(parent, ChildName);
        if (result.equals("true")) {
            return true;
        } else {
            return false;
        }
    }

    protected Document request(URL url, String method, Map params)
            throws IOException {
        Document ret = null;
        //String encodeKey = new BASE64(false).encode(username + ":" + createPassword());
        //String authKey = "Basic " + encodeKey;

        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod(method);
//		con.setRequestProperty("Authorization", authKey);
//		con.setRequestProperty("me2_application_key", this.appKey);
//		con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        con.setDoInput(true);

//        if (method.equals("POST")) {
//            con.setDoOutput(true);
////			String paramstr = buildParameters(params);
//            OutputStream out = con.getOutputStream();
//            out.write(paramstr.getBytes("UTF-8"));
//            out.flush();
//            out.close();
//        }

        InputStream in = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[4096];
        try {
            in = con.getInputStream();
            while (true) {
                int readlen = in.read(buf);
                if (readlen < 1) {
                    break;
                }
                bos.write(buf, 0, readlen);
            }
            String output = new String(bos.toByteArray(), "UTF-8");
            //System.out.println(output);

            this.lastResult = output;
            try {
                ret = docBuilder.parse(new InputSource(new StringReader(output)));
            } catch (SAXException ex) {
                this.lastResult = ex.toString();
            }
        } catch (IOException e) {
            if (con.getResponseCode() == 500) {
                bos.reset();
                InputStream err = con.getErrorStream();
                while (true) {
                    int readlen = err.read(buf);
                    if (readlen < 1) {
                        break;
                    }
                    bos.write(buf, 0, readlen);
                }
                String output = new String(bos.toByteArray(), "UTF-8");
                System.err.println(output);
            }
            throw e;
        } finally {
            if (in != null) {
                in.close();
            }
            if (con != null) {
                con.disconnect();
            }
        }
        return ret;
    }

    protected boolean isAllowedPosition(String pos) {
        if (pos.equals("QB")
                || pos.equals("WR")
                || pos.equals("RB")
                || pos.equals("TE")
                || pos.equals("K")
                || pos.equals("DE")) {
            return true;
        }
        return false;
    }

    protected Object unmarshallXMLToObject(Element element, Class elementClass) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(elementClass);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
//        unmarshaller.setEventHandler(
//                new ValidationEventHandler() {
//                    public boolean handleEvent(ValidationEvent event) {
//                        throw new RuntimeException(event.getMessage(),
//                                event.getLinkedException());
//                    }
//                });
        return unmarshaller.unmarshal(element, elementClass).getValue();
    }

    public String getWeekId() {
        return weekId;
    }

    public void setWeekId(String weekId) {
        this.weekId = weekId;
    }

    public String getPlayerId() {
        return playerId;
    }

    public void setPlayerId(String playerId) {
        this.playerId = playerId;
    }
}
